import datetime
import base64
import hashlib
import requests
import json

from celery import Celery

app = Celery(
    'send_sms',  # 当前模块的名字
    broker='amqp://guest@localhost//',  # 消息队列的url
    # backend='amqp://guest@localhost//',  # 将调用的结果存储到MQ中
    # backend='redis://localhost:6379/5'  # 将调用的结果存储到Redis中
)

AccountSid = '8a216da86eb206c4016ecba955330ded'  # 填写首页上对应的AccountSid
AccountToken = '5630ca82c33345408cb81b7eb5eda7ff'  # 填写首页上对应的AccountToken
AppId = '8a216da86eb206c4016ecba955930df4'  # 填写首页上对应的AppId
ServerPort = '8883'
ServerIP = 'app.cloopen.com'
SoftVersion = '2013-12-26'
Batch = datetime.datetime.now().strftime("%Y%m%d%H%M%S")


@app.task
def send_template_sms(phone, data):
    # 生成sig
    signature = AccountSid + AccountToken + Batch
    # MD5
    sig = hashlib.md5(signature.encode('utf-8')).hexdigest().upper()
    # 拼接URL
    url = "https://" + ServerIP + ":" + ServerPort + "/" + SoftVersion + "/Accounts/" + AccountSid + "/SMS/TemplateSMS?sig=" + sig
    # 生成auth
    src = AccountSid + ":" + Batch
    auth = base64.encodebytes(bytes(src, 'utf-8')).strip()
    # 创建包头
    headers = {
        "Accept": 'application/json',
        'Content-Type': 'application/json;charset=utf-8',
        "Authorization": auth,
    }
    # 创建包体
    body = {
        "to": "".join(phone),
        "appId": AppId,
        "templateId": "1",  # 这里由于是测试，所以模板为1
        "datas": data,
    }
    req = requests.post(url, headers=headers, json=body)
    re_json = json.loads(req.text)  # 最后返回的是json字典
    return re_json
